package cn.zzp.basic.controller;

import cn.zzp.basic.util.FastDfsUtils;
import cn.zzp.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Administrator
 * @description:
 * @date 2022/7/24 18:11
 */
@RestController
@RequestMapping("/fastdfs")
public class FastDfsController {

    /**
     * 文件上传接口
     * @param file
     * @return
     */
    @PostMapping
    public JsonResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            // 获取原始文件名字 ex：CgAIC2LdCCqAWbQ1AAASFoqbf3c296.png
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            // 调用上传方法
            String path = FastDfsUtils.upload(file.getBytes(), extName);

            // 携带路径返回给前端，赋值给logo字段
            return JsonResult.me().setObj(path);

        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me(false);
        }
    }

    /**
     * 文件删除接口  "/fastdfs/?path="+filePath
     * @param path /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg【前端传回参数】
     * @return
     */
    @DeleteMapping
    public JsonResult delete(@RequestParam(value = "path",required = true) String path){
        try {
            // path: /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            String pathTmp = path.substring(1);
            String groupName = pathTmp.substring(0, pathTmp.indexOf("/"));
            String fileName = pathTmp.substring(pathTmp.indexOf("/") + 1);
            // 调用文件删除方法
            FastDfsUtils.delete(groupName,fileName);

            return JsonResult.me();
        }catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me(false);
        }
    }

}
